package top.chengdongqing.mishop.order.payment

import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import org.springframework.http.ResponseEntity
import org.springframework.stereotype.Component
import org.springframework.web.socket.CloseStatus
import org.springframework.web.socket.TextMessage
import org.springframework.web.socket.WebSocketSession
import org.springframework.web.socket.handler.AbstractWebSocketHandler

@Component
class PaySuccessHandler : AbstractWebSocketHandler() {

    private val clients = mutableMapOf<String, WebSocketSession>()

    override fun afterConnectionEstablished(session: WebSocketSession) {
        val orderId = session.attributes["id"] as String?
        orderId?.also { clients[it] = session }
    }

    override fun afterConnectionClosed(session: WebSocketSession, closeStatus: CloseStatus) {
        val orderId = session.attributes["id"] as String?
        orderId?.also { clients.remove(it) }
    }

    fun notifyPaySuccess(orderId: Int) {
        val session = clients[orderId.toString()]
        if (session?.isOpen == true) {
            session.sendMessage(
                TextMessage(
                    jacksonObjectMapper().writeValueAsString(
                        ResponseEntity.ok(null)
                    )
                )
            )
        }
    }
}